package com.miguo.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 自定义倒计时文本控件
 *
 * @author Administrator
 */
public class RemindTimeTextView extends TextView implements Runnable {

    private long mday, mhour, mmin, msecond;// 天，小时，分钟，秒

    private int interval = 0;

    private Long date;
    private Boolean status = false;

    public RemindTimeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RemindTimeTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public RemindTimeTextView(Context context) {
        super(context);
    }

    public boolean isOver() {
        return interval < 10;
    }

    @Override
    public void run() {
        // 标示已经启动
        if (interval > 10) {
            interval--;

            mday = interval / (24 * 3600);// 天
            mhour = interval % (24 * 3600) / 3600;// 小时
            mmin = interval % 3600 / 60;// 分钟
            msecond = interval % 60;// 秒

            StringBuffer strTime = new StringBuffer();
            if (mday > 0) {
                strTime.append(mday + "天");
            }
            if (mhour > 0) {
                strTime.append(mhour + "小时");
            }

            if (mmin > 0) {
                strTime.append(mmin + "分");
            }

            if (msecond > 0) {
                strTime.append(msecond + "秒");
            }
            status = true;
            setText(strTime);
            postDelayed(this, 1000);
        } else {
            status = false;
            setText("活动已开始");
        }
    }

    /**
     * 获取时间差格式(yyyy-MM-dd HH:mm:ss)
     */
    public void setTime(String date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        try {
            Date currentTime = new Date();// 获取现在的时间
            Date beginTime = dateFormat.parse(date);
            interval = (int) ((beginTime.getTime() - currentTime.getTime()) / (1000));// 时间差
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置时间搓，获取时间差
     */
    public void setTime(long time) {
        date = time;
        Date currentTime = new Date();// 获取现在的时间
        long now = currentTime.getTime() / 1000;
        interval = (int) (date - now);// 时间差
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        if (hasWindowFocus && status == true) {
            setTime(date);
            run();
            return;
        }
        removeCallbacks(this);
    }
}